import React, { Component } from 'react';
import { connect } from 'dva';
import { baseUrl,imgUrl } from '../../config/system';
import { Modal, Form, Input, InputNumber,message , Upload, Icon,Button, TreeSelect,Switch,Select } from 'antd';
const TreeNode = TreeSelect.TreeNode;
const FormItem = Form.Item;
const Option = Select.Option;

class AssetTypeModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
  }

  showModelHandler = (e) => {
    if (e) e.stopPropagation();
    this.props.form.resetFields();
    this.setState({
      visible: true,
    });
  };

  hideModelHandler = () => {
    this.setState({
      visible: false,
    });
  };

  okHandler = () => {
    const { onOk } = this.props;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        onOk(values);
        this.hideModelHandler();
      }
    });
  };

  render() {
    const { children, assetType,assetBrand,dispatch,title,item,brandId,imegeUrl} = this.props;
    const { getFieldDecorator,getFieldProps  } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };

    const typeTreeData = (i) => {
      return i.map( d => {
        d.label = d.name;
        d.key = d.id_+'';
        d.value = d.id_+'';
        d.children = d.assetType && d.assetType.length > 0 ? typeTreeData(d.assetType) : [];
        return d;
      })
    }

    const getBrand = data => data.map((item) => {
     return <Option key={item.id_+''}>{item.name}</Option>
    })

    const props = {
      action: baseUrl + '/upload/uploadImg',
      listType: 'picture',
      beforeUpload(file) {    
        const isJPG = file.type === 'image/png' || file.type === 'image/jpeg';
        if (!isJPG) {
          message.error('只能上传图片文件！');
        }
        return isJPG;
      },
      onChange(info) {
    
        let fileList = info.fileList
    
        if (info.file.status === 'done') {
        if(info.file.response.data.success){
          message.success(`${info.file.name } 上传成功`);
          dispatch({
            type: 'assetModel/updateState',
            payload:{imegeUrl:info.file.response.data.fid},
          });
        }else{
          message.success(info.file.response.errorMsg);
        }
          fileList = fileList.filter((file) => {
            return (file.response && file.response.fid);
          })
          //只保留最后一条记录
            fileList = fileList.slice(-1)
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 上传失败`);
        }
        let fildsValue = {}
        fildsValue['file'] = fileList.map((file) => {
          return file;
        })
      },
    };

    return (
        <span>
           
               <Modal
                    maskClosable= {this.props.maskClosable}
                    confirmLoading= {this.props.confirmLoading}
                    title={this.props.title}
                    visible={this.props.visible}
                    onOk={this.okHandler}
                    onCancel={this.props.onCancel}
                    key={this.props.newKey}
              >
              <Form layout='horizontal' onSubmit={this.okHandler}>
                <FormItem style={{marginBottom:'0px'}}>
                  {getFieldDecorator('id',{initialValue:item.id_})(
                    <Input type="hidden"/>
                  )}
                </FormItem> 
                <FormItem
                  {...formItemLayout}
                  hasFeedback
                  label="型号名称"
                >
                  {
                    getFieldDecorator('name', {
                      initialValue: item.name,
                      rules: [
                        { required: true, whitespace: true, message: '请输入型号名称'},
                        { max: 20, message: '型号名称长度请填写 20 字符以内' },
                        ]
                    })(<Input />)
                  }
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  hasFeedback
                  label="资产分类"
                >
                  {
                    getFieldDecorator('typeId', {
                      initialValue: typeof(item.typeId_)=="undefined" ? undefined : item.typeId_ + '',
                      rules: [{
                        required: true, message: '请选择资产分类',
                      }]
                    })(
                      <TreeSelect
                        showSearch
                        treeNodeFilterProp="title"
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        placeholder="请选择资产分类"
                        notFoundContent="无匹配结果"
                        allowClear
                        treeData={typeTreeData(assetType)}
                        treeDefaultExpandAll
                      >
                      </TreeSelect>
                    )
                  }
                </FormItem>

                <FormItem
                  label="品牌"
                  hasFeedback
                  {...formItemLayout}
                >
                  {getFieldDecorator('brandId', {
                    initialValue:brandId?brandId: typeof(item.brandId_)=="undefined" ? undefined : item.brandId_ + '',
                    rules: [
                      { required: true, message: '请选择品牌' },
                    ],
                  })(
                    <Select 
                      placeholder="请选择品牌"
                      showSearch>
                      {getBrand(assetBrand)}
                    </Select>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  hasFeedback
                  label="模型名称"
                >
                  {
                    getFieldDecorator('unityModelPath', {
                      initialValue: item.unityModelPath,
                      rules: [
                        {required: true, whitespace: true, message: '请输入模型名称'},
                        { max: 200, message: '模型名称名称长度请填写 200 字符以内' },
                      ]
                    })(<Input />)
                  }
                  
                </FormItem>
                <FormItem
                  label="上传图片"
                  {...formItemLayout}
                  >
                  <Upload {...props} className="upload-list-inline" showUploadList={false}>
                  <Button type="ghost">
                  <Icon type="upload" /> upload
                  </Button>
                  </Upload>
                  {imegeUrl===null||imegeUrl===''?'':<a href={imgUrl+'/'+imegeUrl} target="_blank" rel="noopener noreferrer" className="upload-example">
                    <img  src={imgUrl+'/'+imegeUrl} style={{width:200,marginTop:12}}/>

                  </a>}
                  {/* <Input type="hidden" {...getFieldProps('pictures',{initialValue:imegeUrl})}/> */}
                  {
                    getFieldDecorator('imgPath', {
                      initialValue: imegeUrl,
                    })(<Input type="hidden" />)
                  }
               </FormItem>


                <FormItem
                  {...formItemLayout}
                  hasFeedback
                  label="U高"
                >               
                  {
                    getFieldDecorator('uHeight', {
                      initialValue: item.uHeight,
                      rules: [{
                        type: 'number', message: 'U高只能为数字格式',
                      }, {
                        required: true, message: '请输入U高',
                      }],
                    })(<InputNumber min={0} />)
                  }
                  </FormItem>

                  <FormItem
                      label="是否柜内设备"
                      hasFeedback
                      {...formItemLayout}
                    >
                      {getFieldDecorator('isInCabinet', {
                        initialValue: item.isInCabinet || false,
                        valuePropName: 'checked',
                        rules: [
                          { type:'boolean', required: true, },
                        ],
                      })(
                        <Switch />
                      )}
                    </FormItem>

               
              </Form>
            </Modal> 
        </span>
    );
  }
}

export default Form.create()(AssetTypeModal);